#include "mainwindow.h"

#include <QApplication>
#include <QDebug>
#include <QGridLayout>
#include <QImage>
#include <QMimeData>
#include <QPixmap>
#include <QPlainTextEdit>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , clipboard(nullptr)
{
    QWidget *centralWidget = new QWidget;
    setCentralWidget(centralWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout;

    QPushButton *btn = new QPushButton(tr("Manual update"));
    connect(btn, &QPushButton::clicked, this, &MainWindow::slotBtnClicked);
    mainLayout->addWidget(btn);

    QLabel *infoLabel;
    infoLabel = new QLabel(tr("Show data in clipboard"));
    infoLabel->setWordWrap(true);
    infoLabel->adjustSize();
    infoLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(infoLabel);

    abstractLabel = new QLabel(tr("Show data in clipboard"));
    abstractLabel->setWordWrap(true);
    abstractLabel->adjustSize();
    abstractLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(abstractLabel);

    QPlainTextEdit *qte = new QPlainTextEdit(this);
    mainLayout->addWidget(qte);

    centralWidget->setLayout(mainLayout);

    setWindowTitle(tr("Preview clipboard"));
    setMinimumSize(350, 500);
    setGeometry(400, 200, 350, 500);

    clipboard = QApplication::clipboard();
    connect(clipboard, &QClipboard::dataChanged, this, &MainWindow::slotDataChanged);
    showData(QString("init"));
}

MainWindow::~MainWindow()
{
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::Clipboard) {
        qDebug() << "Clipboard event";
    } else if (event->type() == QEvent::ShowWindowRequest) {
        qDebug() << "ShowWindowRequest event";
    } else if (event->type() == QEvent::Show) {
        setGeometry(400, 200, 350, 500);
    }

    return QMainWindow::eventFilter(obj, event);
}

void MainWindow::slotDataChanged()
{
    showData(QString("slotDataChanged"));
}

void MainWindow::slotBtnClicked()
{
    showData(QString("slotBtnClicked"));
}

void MainWindow::showData(const QString triggerFrom)
{
    const QMimeData *mimeData = clipboard->mimeData();
    qWarning() << "show data" << mimeData->formats() << "from" << triggerFrom;
    if (mimeData->hasImage()) {
        QPixmap pixmap = qvariant_cast<QPixmap>(mimeData->imageData());
        abstractLabel->setPixmap(pixmap);
    } else if (mimeData->hasHtml()) {
        abstractLabel->setText(mimeData->html());
    } else if (mimeData->hasText()) {
        abstractLabel->setText(mimeData->text());
    } else {
        abstractLabel->setText("cannot display");
    }
}
